<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      class="medium-common-dialog-size">
      <Title title="查看明细" style="margin-bottom: 10px"/>
      <el-table
        v-loading="tableLoading"
        ref="transferTableRef"
        :data="tableData"
        :height="maxHeight"
        :row-key="'id'"
        @select="selectTable"
        @select-all="selectTable">
        <el-table-column
          v-if="!isDetail"
          type="selection"
          align="center"
          width="55" />
        <el-table-column v-for="(item, index) in headData" :key="index" :label="item.label">
          <template slot-scope="scope">
            <div v-if="item.type === 'orderType'">{{ scope.row[item.property] | orderTypeStatusFilter }}</div>
            <div v-else-if="item.type === 'platform'" class="flex">
              <platformIcon :data="scope.row[item.property]" />{{ scope.row[item.property] || '--' }}
            </div>
            <div v-else-if="item.type === 'clientType'">{{ scope.row[item.property] | clientStatusFilter }}</div>
            <div v-else-if="item.type === 'contractType'">{{ scope.row[item.property] | contractType }}</div>
            <div v-else-if="item.type === 'applyBusinessType'">{{ scope.row[item.property] | applyBusinessTypeStatus }}</div>
            <div v-else-if="item.type === 'date'">{{ standardFormat(scope.row[item.property], 'YYYY/MM/DD') }}</div>
            <div v-else-if="item.type === 'minute'">
              <ToolTip :content="formatMinute(scope.row, item)" />
            </div>
            <div v-else-if="item.type === 'month'">{{ standardFormat(scope.row[item.property] / 1000, 'YYYY/MM') }}</div>
            <div v-else-if="item.type === 'signDate'">
              <ToolTip :content="formatSignDate(scope.row)" />
            </div>
            <ToolTip v-else :content="scope.row[item.property]" />
          </template>
        </el-table-column>
        <el-table-column v-if="!noShowTypes.includes(type)" property="name" label="操作" width="60">
          <template slot-scope="scope">
            <el-button type="text" @click="toOrderDetail(scope.row)"><span style="font-size: 14px">查看</span></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex-page">
        <SelectionNum :select-num="selectionNum" @clearMixinSelection="clearAllSelection" />
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :page-sizes="[10, 20, 50]"
          :total="orderData ? orderData.length : 0"
          small
          layout="total, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import platformIcon from '@/components/Common/platformIcon';
import { getWorkflowId, getSupplierId } from '@/api/handover';
import { standardFormat } from '@/filters/date';
import { orderTypeStatusFilter, clientStatusFilter, contractType, applyBusinessTypeStatus } from '@/filters/status';
import tableSelections from '@/mixins/tableSelections';
import { encryption } from '@/utils';

export default {
  components: { Title, platformIcon },
  filters: { orderTypeStatusFilter, clientStatusFilter, contractType, applyBusinessTypeStatus },
  mixins: [tableSelections],
  props: {
    headData: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      maxHeight: '',
      tableLoading: false,
      total: 0,
      page: 1,
      perPage: 10,
      type: 0,
      ids: '',
      orderData: [],
      tableData: [],
      dialogVisible: false,
      isCheck: true, // 初始时是否勾选
      tableRefName: 'transferTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      selectionNum: 0, // 勾选条数
      customModuleId: '',
      isDetail: false, // 是否从详情打开的
      status: '', // 当前是哪个状态
      noShowTypes: [25]
    };
  },
  computed: {
    toTypeMap() {
      return new Map([
        [0, this.toContract],
        [2, this.toEnergy],
        [3, this.toSignUp],
        [4, this.toOriginal],
        [5, this.toIssueInvoice],
        [6, this.toInvoiceAbandon],
        [7, this.toOrder],
        [8, this.toProject],
        [9, this.toSettle],
        [10, this.toSupplier],
        [11, this.toAccount],
        [13, this.toCustomer],
        [14, this.toCost],
        [15, this.toCustomForm],
        [16, this.toReimbursement],
        [17, this.toLoan],
        [18, this.toPayback],
        [19, this.toTransfer],
        [20, this.toTermination],
        [21, this.toFlyNotice],
        [22, this.toFlyPrice],
        [23, this.toAdjustment],
        [24, this.toExternal],
        [26, this.toFilterDetail],
        [27, this.toUpOnline]
      ]);
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val);
        });
      },
      deep: true
    }
  },
  methods: {
    standardFormat,
    formatMinute(row, item) {
      if (!row[item.property]) {
        return '--';
      }
      const temp = `${this.standardFormat(item.millisecond ? row[item.property] / 1000 : row[item.property], 'YYYY/MM/DD HH:mm')}`;
      return temp;
    },
    formatSignDate(row) {
      if (!row.signStartDate) {
        return '--';
      }
      const temp = `${this.standardFormat(row.signStartDate / 1000, 'YYYY/MM/DD')}-${this.standardFormat(row.signEndDate / 1000, 'YYYY/MM/DD')}`;
      return temp;
    },
    async initData(val, row, isCheck = true, isDetail = false) {
      this.isDetail = isDetail;
      this.type = row.businessType;
      this.status = val.status;
      this.customModuleId = !isDetail ? row.id : row.customModuleId; // 自定义表单类型id
      this.orderData = val.fieldInfo;
      this.removeIds = val.removeIds;
      this.handleData(this.orderData);
      this.formId = row.formId;
      this.ids = val.ids.join();
      this.isCheck = isCheck;
      if (this.isCheck) {
        // this.multipleSelectionAll = this.orderData;
        const temp = val.fieldInfo.filter(item => {
          if (val.removeIds.findIndex(ele => ele === item.id) === -1) {
            return item;
          }
        });
        this.multipleSelectionAll = temp;
        this.selectionNum = temp.length;
      }
      this.dialogVisible = true;
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 3) / 5);
    },
    handleData(data) {
      if (!data) return;
      this.tableData = data.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    async getData(resetPage = false) {
      if (resetPage) {
        this.page = 1;
      }
      const params = {
        ids: this.ids,
        page: this.page,
        perPage: this.perPage
      };
      if (this.type === 15) { // 自定义审批加参数
        params.formId = this.formId;
      }
      this.tableLoading = true;
      this.tableLoading = false;
    },
    handleClose() {
      this.$emit('handleClose', { removeIds: this.removeIds, status: this.status, type: this.type });
      this.perPage = 10;
      this.page = 1;
      this.multipleSelectionAll = [];
      this.selectionNum = 0;
      this.removeIds = [];
      this.dialogVisible = false;
    },
    async handleCurrentChange(val) {
      this.page = val;
      this.handleData(this.orderData);
      if (this.isCheck && !this.clearAll) {
        this.multipleSelectionAll = this.multipleSelectionAll.concat(this.tableData);
        this.multipleSelectionAll = this.multipleSelectionAll.filter(i => {
          return !this.removeIds.includes(i.id);
        });
      }
    },
    async handleSizeChange(val) {
      this.perPage = val;
      if (this.isCheck && !this.clearAll) {
        this.multipleSelectionAll = this.multipleSelectionAll.concat(this.tableData);
        this.multipleSelectionAll = this.multipleSelectionAll.filter(i => {
          return !this.removeIds.includes(i.id);
        });
      }
    },
    toContract(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(res.data) },
        query: { processId: encryption(row.id) }
      });
      return routeUrl;
    },
    toEnergy(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'energyDetail',
        query: {
          energyId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toSignUp(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'signUpDetail',
        query: {
          signUpId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toOriginal(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'originalDetail',
        query: {
          originalId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toIssueInvoice(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'issueInvoiceDetail',
        query: {
          issueId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toInvoiceAbandon(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'invoiceAbandonDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toOrder(row) {
      const routeUrl = this.$router.resolve({
        name: 'orderDetail',
        params: { orderId: row.id }
      });
      return routeUrl;
    },
    toProject(row) {
      const routeUrl = this.$router.resolve({
        name: 'projectDetail',
        params: { id: row.id }
      });
      return routeUrl;
    },
    toSettle(row) {
      const routeUrl = this.$router.resolve({
        name: 'settleCustomer',
        params: { id: row.id || 1 }
      });
      return routeUrl;
    },
    toSupplier(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'supplierDetail',
        query: {
          settleId: row.id,
          id: res.data,
          isSettle: true
        }
      });
      return routeUrl;
    },
    toAccount(row) {
      const routeUrl = this.$router.resolve({
        name: 'detailResource',
        params: { resourceId: row.id }
      });
      return routeUrl;
    },
    toCustomer(row) {
      const routeUrl = this.$router.resolve({
        name: 'detailCustomer',
        params: { customerId: row.id }
      });
      return routeUrl;
    },
    toCost(row) {
      const routeUrl = this.$router.resolve({
        name: 'costDetail',
        params: { id: row.id }
      });
      return routeUrl;
    },
    toCustomForm(row) {
      const routeUrl = this.$router.resolve({
        name: 'approvalModuleDetail',
        params: { moduleId: this.customModuleId },
        query: { id: row.id, processId: row.processId }
      });
      return routeUrl;
    },
    toReimbursement(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'reimbursementDetail',
        query: {
          reimbursementId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toLoan(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'loanDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toPayback(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'payBackDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toTransfer(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'arrearsTransferDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toTermination(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'terminationDetail',
        query: {
          terminationId: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toFlyNotice(row) {
      let routeUrl = null;
      if (this.status === 6) {
        routeUrl = this.$router.resolve({
          name: 'flyNotice',
          query: { tabStatus: this.status }
        });
      } else {
        routeUrl = this.$router.resolve({
          name: 'flyNoticeDetail',
          query: { id: row.id }
        });
      }
      return routeUrl;
    },
    toFlyPrice(row) {
      let routeUrl = null;
      if (this.status === 6) {
        routeUrl = this.$router.resolve({
          name: 'flyPrice',
          query: { tabStatus: this.status }
        });
      } else {
        routeUrl = this.$router.resolve({
          name: 'flyPriceDetail',
          query: { id: row.id }
        });
      }
      return routeUrl;
    },
    toAdjustment(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'customerAdjustmentDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toExternal(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'externalHarvestDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toFilterDetail(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'filterDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    toUpOnline(res, row) {
      const routeUrl = this.$router.resolve({
        name: 'upOnlineDetail',
        query: {
          id: res.data,
          processId: row.id
        }
      });
      return routeUrl;
    },
    async toOrderDetail(row) {
      let routeUrl = null;
      if ([0, 2, 3, 4, 5, 6, 10, 16, 17, 18, 19, 20, 23, 24, 26, 27].includes(Number(this.type))) {
        let res = null;
        if (this.type === 10) {
          res = await getSupplierId(row.id);
        } else {
          res = await getWorkflowId(row.id);
        }
        if (res.code === 200) {
          const fn = this.toTypeMap.get(Number(this.type));
          routeUrl = fn(res, row);
        }
      } else {
        const fn = this.toTypeMap.get(Number(this.type));
        routeUrl = fn(row);
      }
      routeUrl !== null && window.open(routeUrl.href, '_blank');
    },
    clearAllSelection() {
      this.clearMixinSelection();
      this.removeIds = this.ids.split(',').map(item => Number(item));
      this.clearAll = true;
      this.selectionNum = 0;
    }
  }
};
</script>

<style lang="scss" scoped>
.flex-page {
  display: flex;
  justify-content: space-between;
}
</style>
